var pathRequestUrl;
var page_size = 20;
var date_format_string = 'd/m/Y';
var date_sql_format_string = 'Y-m-d';
var songRecord;
var songObj;
var gridSong;
var row_current = -1;
var col_current = -1;


Ext.onReady(function(){
    Ext.QuickTips.init();
    pathRequestUrl = 'ListSongData.php';
            
    var render_number = function(val){
        try {
            if (val == null || val == '') 
                val = 0.00;
            return number_format_extra(val, decimals, decimalSeparator, thousandSeparator);
        } 
        catch (e) {
        }
    };
    
    Ext.grid.CheckColumn = function(config){
        Ext.apply(this, config);
        if (!this.id) {
            this.id = Ext.id();
        }
        this.renderer = this.renderer.createDelegate(this);
    };
    
    Ext.grid.CheckColumn.prototype = {
        init: function(grid){
            this.grid = grid;
            this.grid.on('render', function(){
                var view = this.grid.getView();
                view.mainBody.on('mousedown', this.onMouseDown, this);
            }, this);
        },
        
        onMouseDown: function(e, t){
            if (t.className && t.className.indexOf('x-grid3-cc-' + this.id) != -1) {
                e.stopEvent();
                var index = this.grid.getView().findRowIndex(t);
                var record = this.grid.store.getAt(index);
                var checked = !record.data[this.dataIndex];
                record.set(this.dataIndex, checked);
                if (isEmpty(record.data.song_id) || record.data.song_id == 0) {
                    //Insert
                    insertSong(record);
                }
                else {
                    //Update
                    var check_val = checked ? 1 : 0;
                    updateSong(record, this.dataIndex, check_val);
                };
            }
        },
        
        renderer: function(v, p, record){
            p.css += ' x-grid3-check-col-td';
            return '<div class="approved-column x-grid3-check-col' +
            (v ? '-on' : '') +
            ' x-grid3-cc-' +
            this.id +
            '">&#160;</div>';
        }
    };
    
    function isEmpty(obj){
        if (typeof obj == 'undefined' || obj === null || obj === '') 
            return true;
        if (typeof obj == 'number' && isNaN(obj)) 
            return true;
        if (obj instanceof Date && isNaN(Number(obj))) 
            return true;
        return false;
    };
    
    var formatDate = function(value){
        if (isEmpty(value)) 
            return '';
        try {
            return value ? ((value.dateFormat('d/m/Y') != '01/01/1970') ? value.dateFormat('d/m/Y') : '') : '';
        } 
        catch (e) {
            console.debug(e);
        }
    };
    //--------------------------
    function isEmpty(obj){
        if (typeof obj == 'undefined' || obj === null || obj === '') 
            return true;
        if (typeof obj == 'number' && isNaN(obj)) 
            return true;
        if (obj instanceof Date && isNaN(Number(obj))) 
            return true;
        return false;
    };
    //Design delete button for grid
    Ext.ns('Extensive.grid');
    Extensive.grid.ItemDeleter = Ext.extend(Ext.grid.RowSelectionModel, {
        width: 30,
        sortable: false,
        dataIndex: 0, // this is needed, otherwise there will be an error		
        menuDisabled: true,
        fixed: true,
        id: 'deleter',
        initEvents: function(){
            Extensive.grid.ItemDeleter.superclass.initEvents.call(this);
            this.grid.on('cellclick', function(grid, rowIndex, columnIndex, e){
                if (columnIndex == grid.getColumnModel().getIndexById('deleter')) {
                    var record = grid.getStore().getAt(rowIndex);
                    if (record.data.song_id == 0) 
                        return false;
                    Ext.Msg.show({
                        title: 'Xác nhận',
                        buttons: Ext.MessageBox.YESNO,
                        icon: Ext.MessageBox.QUESTION,
                        msg: "Bạn có chắc là muốn xóa <b>" + record.data.song_name + "</b> không ?",
                        fn: function(btn){
                            if (btn == 'yes') {
                                deleteSong(record);
                            }
                        }
                    });
                }
            });
        },
        renderer: function(v, p, record, rowIndex){
            return '<div class="extensive-remove" style="width: 15px; height: 16px;"></div>';
        }
    });
    var itemDeleter = new Extensive.grid.ItemDeleter();
    //Tooltip for row
    var render_song_name_tooltip = function(v, p, a){
        //v : value , p : cell		
        if (isEmpty(v)) 
            return;
        p.attr = 'ext:qtitle="<u>Tên Bài Hát</u>"';
        p.attr += 'ext:qtip="' + v + '"';
        return v;
    };
    var render_singer_tooltip = function(v, p, a){
        //v : value , p : cell		
        if (isEmpty(v)) 
            return;
        p.attr = 'ext:qtitle="<u>Ca Sĩ</u>"';
        p.attr += 'ext:qtip="' + v + '"';
        return v;
    };
    
    var render_song_singer_sing_tooltip = function(v, p, a){
        //v : value , p : cell		
        if (isEmpty(v)) 
            return;
        p.attr = 'ext:qtitle="<u>Song Ca</u>"';
        p.attr += 'ext:qtip="' + v + '"';
        return v;
    };
    
    
    var render_composer_tooltip = function(v, p, a){
        //v : value , p : cell		
        if (isEmpty(v)) 
            return;
        p.attr = 'ext:qtitle="<u>Nhạc Sĩ</u>"';
        p.attr += 'ext:qtip="' + v + '"';
        return v;
    };
    
    //The Loai:----------------------------------------   
    var storeSongType = new Ext.data.Store({
        reader: new Ext.data.JsonReader({
            root: 'data',
            totalProperty: 'count',
            id: 'type_id',
            fields: ['type_id', 'type_number', 'type_name']
        }),
        proxy: new Ext.data.HttpProxy({
            url: pathRequestUrl
        }),
        autoLoad: true
    });
    
    storeSongType.on('beforeload', function(store){
        store.baseParams.action = 'getListSongType';
    });
    
    var render_song_type = function(val){
        try {
            if (isEmpty(val) || (val == 0)) {
                return '';
            }
            
            var songTypeObj = storeSongType.queryBy(function(rec){
                return rec.data.type_id == val;
            }).itemAt(0);
            if (songTypeObj) 
                return songTypeObj.data.type_name;
            return '';
        } 
        catch (e) {
        }
    };
    
    //Ca si:----------------------------------------   
    var storeSinger = new Ext.data.Store({
        reader: new Ext.data.JsonReader({
            root: 'data',
            totalProperty: 'count',
            id: 'object_id',
            fields: ['object_id', 'object_number', 'object_name', 'object_type']
        }),
        proxy: new Ext.data.HttpProxy({
            url: pathRequestUrl
        }),
        autoLoad: false
    });
    
    storeSinger.on('beforeload', function(store){
        store.baseParams.action = 'getListSinger';
    });
    
    //Nhac si:----------------------------------------   
    var storeComposer = new Ext.data.Store({
        reader: new Ext.data.JsonReader({
            root: 'data',
            totalProperty: 'count',
            id: 'object_id',
            fields: ['object_id', 'object_number', 'object_name', 'object_type']
        }),
        proxy: new Ext.data.HttpProxy({
            url: pathRequestUrl
        }),
        autoLoad: false
    });
    
    storeComposer.on('beforeload', function(store){
        store.baseParams.action = 'getListComposer';
    });
    
    //Doi tuong (ca/nhac si):----------------------------------------   
    var storeObject = new Ext.data.Store({
        reader: new Ext.data.JsonReader({
            root: 'data',
            totalProperty: 'count',
            id: 'object_id',
            fields: ['object_id', 'object_number', 'object_name', 'object_type']
        }),
        proxy: new Ext.data.HttpProxy({
            url: pathRequestUrl
        }),
        autoLoad: true
    });
    
    storeObject.on('beforeload', function(store){
        store.baseParams.action = 'getListObject';
    });
    
    var tpl_object = new Ext.XTemplate('<tpl for="."><div class="search-item">', '<span> {object_name}</span><br />', '</div></tpl>');
    
    //Doi tac:----------------------------------------   
    var storePartner = new Ext.data.Store({
        reader: new Ext.data.JsonReader({
            root: 'data',
            totalProperty: 'count',
            id: 'partner_id',
            fields: ['partner_id', 'partner_number', 'partner_name']
        }),
        proxy: new Ext.data.HttpProxy({
            url: pathRequestUrl
        }),
        autoLoad: true
    });
    
    storePartner.on('beforeload', function(store){
        store.baseParams.action = 'getListPartner';
    });
    
    var render_partner_tooltip = function(v, p, a){
        try {
            if (isEmpty(v) || (v == 0)) {
                return '';
            }
            
            var partnerObj = storePartner.queryBy(function(rec){
                return rec.data.partner_id == v;
            }).itemAt(0);
            if (partnerObj && !isEmpty(v)) {
                v = partnerObj.data.partner_name;
                p.attr = 'ext:qtitle="<u>Đối Tác</u>"';
                p.attr += 'ext:qtip="' + v + '"';
                return v;
            }
            return '';
        } 
        catch (e) {
        }
    };
    
    //-----------------------------
    songRecord = [{
        name: 'song_id',
        type: 'string'
    }, {
        name: 'type_id',
        type: 'string'
    }, {
        name: 'partner_id',
        type: 'string'
    }, {
        name: 'singer_id',
        type: 'string'
    }, {
        name: 'singer_name',
        type: 'string'
    }, {
        name: 'song_singer_sing',
        type: 'string'
    }, {
        name: 'composer_id',
        type: 'string'
    }, {
        name: 'composer_name',
        type: 'string'
    }, {
        name: 'song_number',
        type: 'string'
    }, {
        name: 'song_name',
        type: 'string'
    }, {
        name: 'song_unsigned_name',
        type: 'string'
    },
    /*{
        name: 'song_price',
        type: 'string'
    },*/
    {
        name: 'song_singer_authority',
        type: 'string'
    }, {
        name: 'song_composer_authority',
        type: 'string'
    }, {
        name: 'song_release_authority',
        type: 'string'
    }, {
        name: 'created_date',
        type: 'date'
    }, {
        name: 'ended_date',
        type: 'date'
    }];
    
    songObj = Ext.data.Record.create(songRecord);
    
    var song = {
        add: function(){
    		addNewSong();
            //bbarSong.moveLast();
        },
        remove: function(){
        },
        find: function(){
            gridSong.getStore().load();
        },
        print: function(){
			var action = 'export';
			var srch_song_number = Ext.getCmp('srch_song_number').getValue();
			var srch_song_name = Ext.getCmp('srch_song_name').getValue();
			var srch_type_id = Ext.getCmp('srch_type_id').getValue();
			var srch_singer_id = Ext.getCmp('srch_singer_id').getValue();
			var srch_composer_id = Ext.getCmp('srch_composer_id').getValue();
			var srch_partner_id = Ext.getCmp('srch_partner_id').getValue();
			var srch_song_singer_authority = Ext.getCmp('srch_song_singer_authority').getValue();
			var srch_song_composer_authority = Ext.getCmp('srch_song_composer_authority').getValue();
			var srch_song_release_authority = Ext.getCmp('srch_song_release_authority').getValue();        
			var srch_from_update_date = isEmpty(Ext.getCmp('srch_from_update_date').getValue())?'':Ext.getCmp('srch_from_update_date').getValue().dateFormat(date_sql_format_string);
			var srch_to_update_date = isEmpty(Ext.getCmp('srch_to_update_date').getValue())?'':Ext.getCmp('srch_to_update_date').getValue().dateFormat(date_sql_format_string);
            
			window.open(
					pathRequestUrl + '?action=' + action + 
					'&sb=' + srch_song_number +
					'&sn' + srch_song_name +
					'&st=' + srch_type_id +
					'&ss=' + srch_singer_id +
					'&sc=' + srch_composer_id +
					'&pi=' + srch_partner_id +
					'&ssa=' + srch_song_singer_authority +
					'&sca=' + srch_song_composer_authority +
					'&sra=' + srch_song_release_authority +
					'&fcd=' + srch_from_update_date +
					'&tcd=' + srch_to_update_date 
			, null, "height=200,width=400,status=yes,toolbar=no,menubar=no,location=no");
        },
        unExecute: function() {
        	Ext.Msg.show({
                title: 'Cảnh báo',
                buttons: Ext.MessageBox.YESNO,
                icon: Ext.MessageBox.QUESTION,
                msg: "Chức năng này sẽ chuyển tất cả những bài hát từ trạng thái độc quyền sang trạng thái không độc quyền đối với những bài hát " +
                		"đã hết hạn độc quyền tính đến thời điểm hiện tại. Bạn có chắc là muốn thực hiện chức năng này không ?",
                fn: function(btn){
                    if (btn == 'yes') {
                    	unExecuteSong();
                    }
                }
            });
        }        
    };
    
    var storeSong = new Ext.data.Store({
        reader: new Ext.data.JsonReader({
            root: 'data',
            totalProperty: 'count',
            id: 'id'
        }, songObj),
        proxy: new Ext.data.HttpProxy({
            url: pathRequestUrl
        }),
        autoLoad: true
    });
    
    storeSong.on('beforeload', function(){
        storeSong.baseParams.action = 'get';
        storeSong.baseParams.start = 0;
        storeSong.baseParams.limit = page_size;
        storeSong.baseParams.srch_song_number = Ext.getCmp('srch_song_number').getValue();
        storeSong.baseParams.srch_song_name = Ext.getCmp('srch_song_name').getValue();
        storeSong.baseParams.srch_type_id = Ext.getCmp('srch_type_id').getValue();
        storeSong.baseParams.srch_singer_id = Ext.getCmp('srch_singer_id').getValue();
        storeSong.baseParams.srch_composer_id = Ext.getCmp('srch_composer_id').getValue();
        storeSong.baseParams.srch_partner_id = Ext.getCmp('srch_partner_id').getValue();
        storeSong.baseParams.srch_song_singer_authority = Ext.getCmp('srch_song_singer_authority').getValue();
        storeSong.baseParams.srch_song_composer_authority = Ext.getCmp('srch_song_composer_authority').getValue();
        storeSong.baseParams.srch_song_release_authority = Ext.getCmp('srch_song_release_authority').getValue();        
        storeSong.baseParams.srch_from_update_date = isEmpty(Ext.getCmp('srch_from_update_date').getValue())?'':Ext.getCmp('srch_from_update_date').getValue().dateFormat(date_sql_format_string);
        storeSong.baseParams.srch_to_update_date = isEmpty(Ext.getCmp('srch_to_update_date').getValue())?'':Ext.getCmp('srch_to_update_date').getValue().dateFormat(date_sql_format_string);
        
    });
    storeSong.on('load', function(){
        if (gridSong.getStore().getCount() == 0) {
            var newRecord = new songObj({
                song_id: 0,
                type_id: null,
                partner_id: null,
                singer_id: null,
                composer_id: null,
                song_number: null,
                song_name: null,
                song_unsigned_name: null,
                //song_price: null,
                song_singer_authority: 0,
                song_composer_authority: 0,
                song_release_authority: 0
            });
            
            gridSong.getStore().insert(0, newRecord);
        }
    });
    //Type Vote for search:----------------------------------------------
    var typeAuthorities = new Ext.data.SimpleStore({
        data: [[1, 'Quyền ghi âm'], [2, 'Quyền tác giả'], [3, 'Quyền phát hành'], [4, 'Quyền Ghi âm + Tác giả']],
        fields: ['type', 'type_name']
    });
    
    var render_typeObject = function(val){
        try {
            if (val == null || val == '') 
                return '';
            return typeObject.queryBy(function(rec){
                return rec.data.type_vote_id == val;
            }).itemAt(0).data.type_vote_name;
        } 
        catch (e) {
        }
    }
    
	var storeRelease = new Ext.data.ArrayStore({
        data: [[0, 'Không độc quyền'], [1, 'Độc quyền']],
        fields: ['song_release_authority', 'song_release_authority_name']
    });
    
    var tbarSong = new Ext.Panel({
        items: [{
            xtype: 'toolbar',
            id: 'tbar1',
            items: [{
                xtype: 'tbtext',
                width: 40,
                text: 'Mã BH: '
            }, {
                xtype: 'textfield',
                id: 'srch_song_number',
                width: 117,
                listeners: {
                    change: function(e){
						gridSong.getStore().load();
                    }
                }
            }, '-', {
                xtype: 'tbtext',
                width: 45,
                text: 'Tên BH: ',
            }, {
                xtype: 'textfield',
                id: 'srch_song_name',
                width: 150,
                listeners: {
                    change: function(e){
						gridSong.getStore().load();
                    }
                }
            }, '-', {
                xtype: 'tbtext',
                width: 50,
                text: 'Thể Loại: ',
            }, new Ext.form.ComboBox({
                id: 'srch_type_id',
                typeAhead: true,
                store: storeSongType,
                valueField: 'type_id',
                displayField: 'type_name',
                mode: 'local',
                forceSelection: true,
                triggerAction: 'all',
                editable: true,
                width: 150,
                //minListWidth: 150,
                lazyRender: true,
                selectOnFocus: true,
                allowBlank: true,
                listeners: {
                    select: function(combo, record, index){
                    
                    },
                    change: function(e){
						gridSong.getStore().load();
                    }
                }
            }), '-', {
                xtype: 'tbtext',
                width: 70,
                text: 'Ngày KD: ',
            }, {
                xtype: 'tbtext',
                width: 25,
                text: 'Từ ',
            }, {
				xtype: 'datefield',
                width: 80,
                id: 'srch_from_update_date',
                format: date_format_string,
                selectOnFocus: true,
                listeners: {
                    change: function(e){
            			gridSong.getStore().load();
                    }
                }
			}, '-', {
                xtype: 'tbtext',
                width: 30,
                text: 'Đến ',
            }, {
				xtype: 'datefield',
                width: 80,
                id: 'srch_to_update_date',
                format: date_format_string,
                selectOnFocus: true,
                listeners: {
                    change: function(e){
            			gridSong.getStore().load();
                    }
                }
			}]
        }, {
            xtype: 'toolbar',
            id: 'tbar2',
            items: [{
                xtype: 'tbtext',
                width: 40,
                text: 'Ca Sĩ: ',
            }, new Ext.form.ComboBox({
                id: 'srch_singer_id',
                store: storeSinger,
                forceSelection: true,
                valueField: 'object_id',
                displayField: 'object_name',
                typeAhead: false,
                triggerAction: 'all',
                pageSize: 50,
                tpl: tpl_object,
                selectOnFocus: true,
                editable: true,
                width: 117,
                listWidth: 250,
                lazyRender: true,
                itemSelector: 'div.search-item',
                minChars: 1,
                allowBlank: true,
                listeners: {
                    select: function(combo, record, index){
                        //gridSong.getStore().getAt(row_current).data.song_id = record.data.object_id;
                    },
                    change: function(e){
            			gridSong.getStore().load();
                    }
                }
            }), '-', {
                xtype: 'tbtext',
                width: 45,
                text: 'Nhạc Sĩ: ',
            }, new Ext.form.ComboBox({
                id: 'srch_composer_id',
                store: storeComposer,
                forceSelection: true,
                valueField: 'object_id',
                displayField: 'object_name',
                typeAhead: false,
                triggerAction: 'all',
                pageSize: 50,
                tpl: tpl_object,
                selectOnFocus: true,
                editable: true,
                width: 117,
                listWidth: 250,
                lazyRender: true,
                itemSelector: 'div.search-item',
                minChars: 1,
                allowBlank: true,
                listeners: {
                    select: function(combo, record, index){
                    
                    },
                    change: function(e){
            			gridSong.getStore().load();
                    }
                }
            }), '-', {
                xtype: 'tbtext',
                width: 50,
                text: 'Đối Tác: ',
            }, new Ext.form.ComboBox({
                id: 'srch_partner_id',
                typeAhead: true,
                store: storePartner,
                valueField: 'partner_id',
                displayField: 'partner_name',
                mode: 'local',
                forceSelection: true,
                triggerAction: 'all',
                editable: true,
                width: 130,
                //minListWidth: 250,
                lazyRender: true,
                selectOnFocus: true,
                allowBlank: true,
                listeners: {
                    select: function(combo, record, index){
                    
                    },
                    change: function(e){
            			gridSong.getStore().load();
                    }
                }
            }), '-', {
                xtype: 'tbtext',
                width: 50,
                text: 'Quyền: '
            }, {
                xtype: 'checkbox',
                boxLabel: 'Ghi Âm ',
                width: 70,
                id: 'srch_song_singer_authority',
                inputValue: '1',
                listeners: {
                    change: function(e){
            			gridSong.getStore().load();
                    }
                }
            }, {
                xtype: 'checkbox',
                boxLabel: 'Tác Giả ',
                id: 'srch_song_composer_authority',
                inputValue: '2',
                listeners: {
                    change: function(e){
            			gridSong.getStore().load();
                    }
                }
            }, '-', {
                xtype: 'tbtext',
                width: 65,
                text: 'Độc Quyền: '
            }, new Ext.form.ComboBox({
                id: 'srch_song_release_authority',
                store: storeRelease,
                forceSelection: true,
                displayField: 'song_release_authority_name',
                valueField: 'song_release_authority',
                typeAhead: false,
                triggerAction: 'all',
                mode: 'local',
                allowBlank: true,
                editable: true,
                width: 100,
                minListWidth: 100,
                lazyRender: true,
                selectOnFocus: true,
                listeners: {
                    select: function(combo, record, index){
                    
                    },
                    change: function(e){
                    	gridSong.getStore().load();
                    }
                }
            })/*, {
                //xtype: 'checkbox',
                xtype: 'hidden',
                boxLabel: 'Quyền Phát Hành ',
                id: 'srch_song_release_authority',
                inputValue: '3',
                listeners: {
                    change: function(e){
            			gridSong.getStore().load();
                    }
                }
            }*/, '->', {
                text: 'Tìm Kiếm',
                id: 'find_song_action',
                cls: 'x-btn-text-icon',
                icon: 'images/icons/find.png',
                style: 'padding-left: 5px;',
                handler: song.find
            }]
        }, {
            xtype: 'toolbar',
            id: 'tbar3',
            items: [{
                text: 'Hủy Độc Quyền',
                id: 'unexecute',
                cls: 'x-btn-text-icon',
                icon: 'images/icons/icon_wand.gif',
                style: 'padding-left: 5px;',
                handler: song.unExecute
            }, '-', {
                xtype: 'tbtext',
                width: 80,
                text: 'Ngày hết hạn: '
            }, {
				xtype: 'datefield',
                width: 80,
                value: new Date(),
                id: 'execute_to_date',
                format: date_format_string,
                selectOnFocus: true,
                listeners: {
                    change: function(e){
            			
                    }
                }
			}, '->', {
                text: 'Thêm',
                id: 'add_song',
                cls: 'x-btn-text-icon',
                icon: 'images/icons/add.png',
                handler: song.add
            }, '-', {
                text: 'In',
                id: 'printer_add',
                cls: 'x-btn-text-icon',
                icon: 'images/icons/printer.png',
                handler: song.print
            }]
        }]
    });
    
    var cmbPerPage = new Ext.form.ComboBox({
        name: 'perpage',
        width: 80,
        store: new Ext.data.SimpleStore({
            data: [[20, '20'], [50, '50'], [100, '100'], [300, '300'], [500, '500'], [1000, '1000']],
            id: 0,
            fields: ['id', 'value']
        }),
        mode: 'local',
        value: '20',
        listWidth: 80,
        triggerAction: 'all',
        displayField: 'value',
        valueField: 'value',
        editable: false,
        forceSelection: true
    });
    
    cmbPerPage.on('select', function(combo, record){
        bbarSong.pageSize = parseInt(record.get('id'), 10);
        bbarSong.doLoad(bbarSong.cursor);
    }, this);
    
    var bbarSong = new Ext.PagingToolbar({
        store: storeSong, // the store you use in your grid
        displayInfo: true,
        pageSize: page_size,
        id: 'bbar_song',
        items: ['-', 'Số tin', cmbPerPage],
        listeners: {
            change: function(tb, data){
//                if (data.activePage == data.pages) {
//                    if (gridSong.getStore().getCount() > 1) {
//                        addNewSong();
//                    }
//                }
            }
        }
    });
    
    var songSingerAuthority = new Ext.grid.CheckColumn({
        header: 'Quyền ghi âm',
        dataIndex: 'song_singer_authority',
        width: 90
    });
    
    var songComposerAuthority = new Ext.grid.CheckColumn({
        header: 'Quyền tác giả',
        dataIndex: 'song_composer_authority',
        width: 90
    });
    
    var songReleaseAuthority = new Ext.grid.CheckColumn({
        header: 'Độc quyền',
        dataIndex: 'song_release_authority',
        width: 90
    });
    
    var cmObject = new Ext.grid.ColumnModel({
        defaults: {
            sortable: true
        },
        columns: [new Ext.grid.RowNumberer(), itemDeleter, {
            header: 'Mã Bài Hát',
            dataIndex: 'song_number',
            width: 100,
            editor: new Ext.form.TextField({
                allowBlank: false,
                selectOnFocus: true,
                enableKeyEvents: true,
                listeners: {
                    keypress: function(my, e){
                        keyCustom(e);
                    }
                }
            })
        }, {
            header: 'Tên Bài Hát',
            dataIndex: 'song_name',
            width: 200,
            renderer: render_song_name_tooltip,
            editor: new Ext.form.TextField({
                allowBlank: false,
                selectOnFocus: true,
                enableKeyEvents: true,
                listeners: {
                    keypress: function(my, e){
                        keyCustom(e);
                    }
                }
            })
        }, {
            header: 'Thể Loại',
            dataIndex: 'type_id',
            width: 120,
            renderer: render_song_type,
            editor: new Ext.form.ComboBox({
                typeAhead: true,
                store: storeSongType,
                valueField: 'type_id',
                displayField: 'type_name',
                mode: 'local',
                forceSelection: true,
                triggerAction: 'all',
                editable: true,
                width: 150,
                lazyRender: true,
                selectOnFocus: true,
                allowBlank: false,
                listeners: {
                    select: function(combo, record, index){
                        gridSong.startEditing(row_current, col_current);
                    }
                }
            })
        }, {
            header: 'Ca Sĩ',
            dataIndex: 'singer_name',
            width: 120,
            renderer: render_singer_tooltip,
            editor: new Ext.form.ComboBox({
                store: storeSinger,
                forceSelection: true,
                valueField: 'object_name',
                displayField: 'object_name',
                typeAhead: false,
                triggerAction: 'all',
                pageSize: 50,
                tpl: tpl_object,
                selectOnFocus: true,
                editable: true,
                width: 117,
                listWidth: 250,
                lazyRender: true,
                itemSelector: 'div.search-item',
                minChars: 1,
                allowBlank: true,
                listeners: {
                    select: function(combo, record, index){
                        gridSong.getStore().getAt(row_current).data.singer_id = record.data.object_id;
                        gridSong.startEditing(row_current, col_current);
                    }
                }
            })
        }, {
            header: 'Song Ca',
            dataIndex: 'song_singer_sing',
            width: 200,
            renderer: render_song_singer_sing_tooltip,
            editor: new Ext.form.TextField({
                allowBlank: false,
                selectOnFocus: true,
                enableKeyEvents: true,
                listeners: {
                    keypress: function(my, e){
                        keyCustom(e);
                    }
                }
            })
        }, {
            header: 'Nhạc Sĩ',
            dataIndex: 'composer_name',
            width: 120,
            renderer: render_composer_tooltip,
            editor: new Ext.form.ComboBox({
                store: storeComposer,
                forceSelection: true,
                valueField: 'object_name',
                displayField: 'object_name',
                typeAhead: false,
                triggerAction: 'all',
                pageSize: 50,
                tpl: tpl_object,
                selectOnFocus: true,
                editable: true,
                width: 117,
                listWidth: 250,
                lazyRender: true,
                itemSelector: 'div.search-item',
                minChars: 1,
                allowBlank: true,
                listeners: {
                    select: function(combo, record, index){
                        gridSong.getStore().getAt(row_current).data.composer_id = record.data.object_id;
                        gridSong.startEditing(row_current, col_current);
                    }
                }
            })
        }, {
            header: 'Đối Tác',
            dataIndex: 'partner_id',
            width: 200,
            renderer: render_partner_tooltip,
            editor: new Ext.form.ComboBox({
                typeAhead: true,
                store: storePartner,
                valueField: 'partner_id',
                displayField: 'partner_name',
                mode: 'local',
                forceSelection: true,
                triggerAction: 'all',
                editable: true,
                width: 183,
                //minListWidth: 250,
                lazyRender: true,
                selectOnFocus: true,
                allowBlank: true,
                listeners: {
                    select: function(combo, record, index){
                        gridSong.startEditing(row_current, col_current);
                    }
                }
            })
        },
        /*{
            header: 'Giá',
            dataIndex: 'song_price',
            renderer: render_number,
            width: 100,
            editor: new Ext.form.TextField({
                allowBlank: false,
                selectOnFocus: true,
                enableKeyEvents: true,
                listeners: {
                    keypress: function(my, e){
                        if (!forceNumber(e)) 
                            e.stopEvent();
                        keyCustom(e);
                    }
                }
            })
        },*/
        {
			header: 'Ngày KD',
            dataIndex: 'created_date',
            width: 100,
            renderer: formatDate,
			editor: new Ext.form.DateField({
				allowBlank: true,
				selectOnFocus: true,
				format: date_format_string
			})
		}, {
			header: 'Ngày Hết Hạn',
            dataIndex: 'ended_date',
            width: 100,
            renderer: formatDate,
			editor: new Ext.form.DateField({
				allowBlank: true,
				selectOnFocus: true,
				format: date_format_string
			})
		}, songSingerAuthority, songComposerAuthority, songReleaseAuthority,
        
        {
            dataIndex: 'song_id',
            hidden: true
        }        /*, {
         dataIndex: 'type_id',
         hidden: true
         }, {
         dataIndex: 'partner_id',
         hidden: true
         }*/
        , {
            dataIndex: 'singer_id',
            hidden: true
        }, {
            dataIndex: 'composer_id',
            hidden: true
        }]
    });
    gridSong = new Ext.grid.EditorGridPanel({
        title: '',
        id: 'gridSong',
        store: storeSong,
        cm: cmObject,
        tbar: tbarSong,
        bbar: bbarSong,
        stripeRows: true,
        height: 600,
        loadMask: true,
        trackMouseOver: true,
        frame: true,
        clicksToEdit: 1,
        selModel: itemDeleter,
		viewConfig: {
            forceFit: true,
            deferEmptyText: true,
            emptyText: 'No records found'
        },
        plugins: [songSingerAuthority, songComposerAuthority, songReleaseAuthority],
        listeners: {
            beforeedit: function(e){
                row_current = e.row;
                col_current = e.column;
            },
            afteredit: function(e){
                if (0 == e.record.data.song_id) {
                    insertSong(e.record);
                }
                else {
                    updateSong(e.record, e.field, e.value);
                }
            }
        }
    });
    
    var songFormPanel = new Ext.FormPanel({
        id: 'list_song_panel',
        iconCls: 'form-icon',
        title: 'Danh Sách Bài Hát',
        frame: true,
        width: 1000,
        renderTo: 'list_song',
        items: [gridSong]
    });
    
});

/**
 * Functions --------------------------------------------------------------------------------------
 */
var addNewSong = function(){
    var newRecord = new songObj({
        song_id: 0,
        type_id: null,
        partner_id: null,
        singer_id: null,
        singer_name: null,
        composer_id: null,
        composer_name: null,
        song_number: null,
        song_name: null,
        song_singer_sing: null,
        song_unsigned_name: null,
        //song_price: null,
        song_singer_authority: false,
        song_composer_authority: false,
        song_release_authority: false,
        created_date: new Date(),
        ended_date: null
    });
    
    gridSong.getStore().insert(gridSong.getStore().getCount(), newRecord);
    gridSong.startEditing(gridSong.getStore().getCount() - 1, 2);
};


/**
 * Insert
 * @author huudatxm
 */
var insertSong = function(record){
    if (!checkDataInsert(record)) 
        return;
    
    var song_singer_authority = record.data.song_singer_authority ? 1 : 0;
    var song_composer_authority = record.data.song_composer_authority ? 1 : 0;
    var song_release_authority = record.data.song_release_authority ? 1 : 0;
    //var song_price = record.data.song_price ? formatNumber(record.data.song_price) : 0;
    var created_date = record.data.created_date ? record.data.created_date.dateFormat(date_sql_format_string) : '';
    var ended_date = record.data.ended_date ? record.data.ended_date.dateFormat(date_sql_format_string) : '';
    
    Ext.Ajax.request({
        url: pathRequestUrl,
        method: 'post',
        success: function(res, opt){
            var result = Ext.decode(res.responseText);
            if (result.data) {
            	if(result.data.error == 1) {
            		alert('Mã bài hát này đã tồn tại. Vui lòng chọn mã khác !.');
            		gridSong.startEditing(row_current, 2);
            		return;
            	}
            	
                record.data.song_id = result.data;
                record.commit();
                
            }
        },
        failure: function(response, request){
            var data = Ext.decode(response.responseText);
            if (!data.success) {
                alert(data.error);
                return;
            }
        },
        params: {
            action: 'insert',
            type_id: record.data.type_id,
            partner_id: record.data.partner_id,
            singer_id: record.data.singer_id,
            composer_id: record.data.composer_id,
            song_number: record.data.song_number,
            song_name: record.data.song_name,
            song_singer_sing: record.data.song_singer_sing,
            //song_price: song_price,
            song_singer_authority: song_singer_authority,
            song_composer_authority: song_composer_authority,
            song_release_authority: song_release_authority,
            created_date: created_date,
            ended_date: ended_date
        }
    });
};

/**
 * Check data for insert
 * @author huudatxm
 */
var checkDataInsert = function(record){
    var data = record.data;
    return !(isEmpty(data.song_number) || isEmpty(data.song_name) || isEmpty(data.singer_id) ||
    isEmpty(data.composer_id) ||
    isEmpty(data.created_date) ||
    !(data.song_singer_authority || data.song_composer_authority || data.song_release_authority) ||
    isEmpty(data.partner_id));
};

/**
 * Key Control
 * @author datnh
 */
var keyCustom = function(e){
    if (e.keyCode == 40) {
        //KeyDown	
        var store_size = gridSong.getStore().getCount();
        if ((store_size - 1) == row_current) {
            if (0 == gridSong.getStore().getAt(store_size - 1).data.song_id) {
                return false;
            }else{
            	addNewSong();
            	return;
            }
        }
        row_current++;
        gridSong.startEditing(row_current, col_current);
        gridSong.getSelectionModel().selectRow(row_current);
    }
    else 
        if (e.keyCode == 38) {
            //KeyUp
            if (row_current > 0) {
                row_current--;
                gridSong.startEditing(row_current, col_current);
                gridSong.getSelectionModel().selectRow(row_current);
            }
        }
};

/**
 * Update
 * @author huudatxm
 */
var updateSong = function(record, field, value){
    if (!checkDataInsert(record)) return;
    if (field == 'singer_name') {
        field = 'singer_id';
        value = record.data.singer_id;
    }else if(field == 'composer_name') {
        field = 'composer_id';
        value = record.data.composer_id;
    };
    Ext.Ajax.request({
        url: pathRequestUrl,
        method: 'post',
        success: function(res, opt){
            var result = Ext.decode(res.responseText);
            if (result.data) {
            	if(result.data.error == 1) {
            		alert('Mã bài hát này đã tồn tại. Vui lòng chọn mã khác !.');
            		gridSong.startEditing(row_current, 2);
            		return;
            	}
                record.commit();
            }
        },
        failure: function(response, request){
            var data = Ext.decode(response.responseText);
            if (!data.success) {
                alert(data.error);
                return;
            }
        },
        params: {
            action: 'update',
            field: field,
            value: value,
            song_id: record.data.song_id,
			partner_id: record.data.partner_id
        }
    });
};

/**
 * Delete
 * @author huudatxm
 */
var deleteSong = function(record){
    Ext.Ajax.request({
        url: pathRequestUrl,
        method: 'post',
        success: function(res, opt){
            var result = Ext.decode(res.responseText);
            if (result.data) {
                gridSong.getStore().remove(record);
                gridSong.getView().refresh();
            }
            else {
                alert('Không thể xóa vì lỗi phát sinh.');
            }
        },
        failure: function(response, request){
            var data = Ext.decode(response.responseText);
            if (!data.success) {
                alert(data.error);
                return;
            }
        },
        params: {
            action: 'delete',
            song_id: record.data.song_id
        }
    });
};

var unExecuteSong = function() {
	if(isEmpty(Ext.getCmp('execute_to_date').getValue())) {
		alert('Bạn chưa chọn ngày hết hạn !.');
		return;
	}
	
	var ended_date = Ext.getCmp('execute_to_date').getValue().dateFormat(date_sql_format_string);
	
	Ext.Ajax.request({
        url: pathRequestUrl,
        method: 'post',
        success: function(res, opt){
            var result = Ext.decode(res.responseText);
            if (result.data) {
                gridSong.getStore().load();    
                alert('Đã chuyển thành công.');
            }
            else {
                alert('Lỗi trong quá trình thực thi. Liên hệ admin để biết thêm chi tiết !.');
            }
        },
        failure: function(response, request){
            var data = Ext.decode(response.responseText);
            if (!data.success) {
                alert(data.error);
                return;
            }
        },
        params: {
            action: 'unExecuteSong',
            ended_date: ended_date
        }
    });
};
